import Logo from '@/layouts/components/Logo';
import { Layout } from 'antd';
import React, { useEffect } from 'react';
import style from './index.less';
import { useModel } from '@umijs/max';
import Menu from '@/layouts/components/Menu';
import { useLocation } from '@@/exports';

const { Sider } = Layout;

export default (props: any) => {
    const { collapsed = false, dark } = props;
    const { initialState } = useModel('@@initialState');
    const routes = initialState?.routes;
    const location = useLocation();
    const currentRoute: any[] = [];
    const flatRoute = (routeTree: any[]) => {
        routeTree.forEach((route: any) => {
            currentRoute.push(route);
            if (route.routes) {
                flatRoute(route.routes);
            }
        });
    };
    flatRoute(routes);
    const getBreadcrumbItems = () => {
        const pathSegments = location.pathname.split('/').filter((segment: any) => segment);
        const items: any = [];
        let currentPath = '';

        pathSegments.forEach((segment: any, index: string | number | bigint | undefined) => {
            currentPath += `/${segment}`;
            const route = currentRoute.find((r: { path: string }) => r.path === currentPath);
            if (route) {
                items.push(route.path);
            }
        });
        return items;
    };

    const items = getBreadcrumbItems();
    const defaultOpenKeys = items;
    const defaultSelectedKeys = [items.pop()];
    return (
        <Sider
            className={style.sideBar}
            width={256}
            theme={dark ? 'dark' : 'light'}
            collapsible
            collapsed={collapsed}
            trigger={null}
        >
            <Logo dark={dark} collapsed={collapsed} />
            <Menu
                className={style.menu}
                dark={dark}
                routes={routes}
                defaultSelectedKeys={defaultSelectedKeys}
                defaultOpenKeys={defaultOpenKeys}
            />
        </Sider>
    );
};
